package com.largeOrange.ajaxclass;

import com.alibaba.fastjson2.JSON;
import com.largeOrange.pojo.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 大橙子
 * @version 1.0
 * @since 1.0
 */
@WebServlet("/request02")
public class AjaxServlet002 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html,charset=UTF-8");
        Connection connection=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取数据库连接对象
            connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/resource","root","012089");
            //预编译sql语句
            String sql="select * from t_user";
            //给属性赋值
            ps=connection.prepareStatement(sql);
            //执行sql语句
            rs=ps.executeQuery();
            //处理查询结果集
            List<User> users = new ArrayList<>();
            while (rs.next()) {
                String userName = rs.getString("userName");
                String passWord = rs.getString("passWorld");
                User user = new User();
                user.setUserName(userName);
                user.setPassWord(passWord);
                users.add(user);
            }
            String jsonString = JSON.toJSONString(users);
            PrintWriter writer = response.getWriter();
            writer.print(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //释放资源
        if (connection!=null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (ps!=null) {
            try {
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
